<template>
  <div>
    <Menu menuActive="/blog" />
    <layout>
      <template v-slot:main>
        <el-row :gutter="20">
          <el-col :lg="16" :md="18">
            <div>
              <el-card class="box-card" shadow="never">
                <template #header>
                  <div class="card-header">
                    <span>上传文章</span>
                  </div>
                </template>
                <div>
                  <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" status-icon
                    size="large">
                    <el-form-item label="标题" prop="title">
                      <el-input v-model="ruleForm.title" placeholder="请输入文章标题" />
                    </el-form-item>
                    <el-form-item label="方向" prop="directionId">
                      <el-select v-model="ruleForm.directionId" placeholder="请选择方向" @change="handleChangeDirect">
                        <el-option v-for="item in directOptions" :key="item.value" :label="item.label"
                          :value="item.value" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="分类" prop="groups">
                      <el-select v-model="ruleForm.groups" placeholder="请选择分类" multiple collapse-tags>
                        <el-option v-for="item in groupOptions" :key="item.value" :label="item.label"
                          :value="item.value" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="描述" prop="description">
                      <el-input v-model="ruleForm.description" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
                        placeholder="请输入文章描述" />
                    </el-form-item>
                    <el-form-item label="封面图" prop="coverPicture">
                      <upload-image :limit="1" @input="handleUploadImage" v-model="ruleForm.coverPicture"></upload-image>
                    </el-form-item>
                    <el-form-item label="类型" prop="type">
                      <el-radio-group v-model="ruleForm.type" @change="handleChangeType">
                        <el-radio :label="0">word</el-radio>
                        <el-radio :label="1">markdown</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item label="内容" prop="content">
                      <editor v-if="ruleForm.type === 0" v-model="ruleForm.content" :min-height="500" :height="500" />
                      <MDEditor v-else v-model="ruleForm.content" :height="500" />
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" style="width:300px" :loading="btnLoading"
                        @click="submitForm(ruleFormRef)">发布</el-button>
                      <el-button @click="() => { $router.go(-1) }">返回</el-button>
                    </el-form-item>
                  </el-form>
                </div>
              </el-card>
            </div>
          </el-col>
          <el-col :lg="8" :md="6">
            <el-card class="box-card" shadow="never">
              <template #header>
                <div class="card-header">
                  <span>相似文章（请勿重复上传）</span>
                </div>
              </template>
              <div v-loading="listLoading" element-loading-text="正在玩命加载中...">
                <span style="font-size:14px;color:#666" v-if="(blogData.data.value.length <= 0)">输入文章标题后将自动检测</span>
                <Article v-for="item in blogData.data.value" :needCoverPicture="false" :title="item.title"
                  :key="item.id" :id="item.id" :description="item.description" :groups="item.groups"
                  :likeNum="item.likeNum" :nickName="item.user.nickName" :commentCount="item.commentCount"
                  :pageViewNum="item.pageViewNum" :needCreateTime="false" />
                <div class="pagination_container">
                  <el-pagination v-model:current-page="searchParams.pageNum" v-model:page-size="searchParams.pageSize"
                    background layout="total, prev, next" :total="blogData.total.value"
                    v-if="blogData.total.value > 0" @current-change="handleCurrentChange" />
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </template>
    </layout>
    <Footer />
  </div>
</template>

<script lang="ts" setup>
import { getDirection, getGroup } from "@/api/dictionary";
import Menu from '@/components/Menu/index.vue'
import Layout from '@/components/Layout/index.vue'
import Footer from '@/components/Footer/index.vue'
import { onMounted, reactive, ref, toRefs, watch } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import uploadImage from '@/components/Upload/index.vue'
import editor from '@/components/QuillEditor/index.vue'
import MDEditor from '@/components/MdEditor/index.vue'
import { publishArtcile } from '@/api/article'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getBlogList } from "@/api/index";
import Article from '@/components/Article/index.vue'
const directOptions = ref<any>([])
const groupOptions = ref<any>([])
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  title: '',
  directionId: '',
  groups: '',
  coverPicture: '',
  type: 0,
  content: '',
  description: ''
})
const rules = reactive<FormRules>({
  title: [
    { required: true, message: '标题不能为空', trigger: 'blur' },
    { min: 1, max: 20, message: '标题字数只能在1-20之间', trigger: 'blur' },
  ],
  directionId: [
    { required: true, message: '请选择方向', trigger: 'blur' },
  ],
  groups: [
    { required: true, message: '请选择分类', trigger: 'blur' },
  ],
  type: [
    { required: true, message: '请选择类型', trigger: 'blur' },
  ],
  content: [{
    required: true, message: '内容不能为空', trigger: 'blur'
  }]
})
const btnLoading = ref<boolean>(false)
const listLoading = ref<boolean>(false)
const searchParams = reactive<any>({
  pageNum: 1,
  pageSize: 3,
  title: ''
})
const blogData = toRefs(reactive<any>({
  data: [],
  total: 0
}))
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // console.log(ruleForm);
      // console.log('submit!'
      try {
        btnLoading.value = true
        if (ruleForm.groups) {
          console.log(ruleForm.groups);

          ruleForm.groups = ruleForm.groups.toString()
        }
        const res: any = await publishArtcile(ruleForm)
        if (res) {
          ElMessage({
            message: '发布成功',
            type: 'success',
            duration: 2 * 1000
          })
          // resetForm(formEl)
          location.reload()
        }

      } finally {
        btnLoading.value = false
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
const handleChangeDirect = (value: number) => {
  console.log(value);
  getGroupOptionsData(value)
}
const getDirectOptionsData = async () => {
  const { data }: any = await getDirection()
  directOptions.value = data.map((item: { id: number; name: string; }) => ({ value: item.id, label: item.name }))
}
const getGroupOptionsData = async (id: number) => {
  const { data }: any = await getGroup()
  let filterArr = data.filter((item: { directionId: number | null }) => {
    return item.directionId === id
  })
  groupOptions.value = filterArr.map((item: { id: any; name: any; }) => ({ value: item.id, label: item.name }))

}
const handleUploadImage = (file: string) => {
  ruleForm.coverPicture = file
}
const handleChangeType = () => {
  ruleForm.content = ''
}
onMounted(() => {
  getDirectOptionsData()
})
const getBlogListData = async () => {
  try {
    listLoading.value = true
    const { rows, total }: any = await getBlogList(searchParams)
    blogData.data.value = rows
    blogData.total.value = total
  } finally {
    listLoading.value = false
  }
}
const handleCurrentChange = (val: number) => {
  searchParams.pageNum = val
  getBlogListData()
}
watch(ruleForm, (newValue, oldValue) => {
  const { title } = newValue
  searchParams.title = title
  if (title) {
    getBlogListData()
  } else {
    blogData.data.value = []
  }
  // console.log("新值是"+newValue, "旧址是"+oldValue);
})
</script>

<style scoped lang="scss">
@import './index.scss';

.pagination_container {
  display: flex;
  justify-content: flex-end;
  margin-top: 40px;
}
</style>
